/**
 * @file PencilTool.cpp
 *
 * @date 17/12/2011
 * @author Tales 
 *
 */

#include "PencilTool.hpp"
//#include <SDL_gfxPrimitives.h>
#include "Editor.hpp"
#include "../common/util.hpp"
#include "../model/DrawLinesCommand.hpp"
#include "../model/Picture.hpp"
#include "../Graphics.hpp"

namespace yep
{

PencilTool::PencilTool()
{
}

PencilTool::~PencilTool()
{
}

void PencilTool::start()
{
	drawing = false;
	Editor &editor = getEditor();
	SDL_FillRect(editor.getPreview(), NULL, 0x0);
}

void PencilTool::end()
{
	vertices.clear();
}

void PencilTool::pressed(pair<int, int> pos, bool leftButton, bitset<5> state)
{
	if (leftButton)
	{
		drawing = true;
		vertices.push_back(pos);
		Editor &editor = getEditor();

		Graphics g(editor.getPreview());
		g.setColor(editor.getColor());
		g.drawPixel(pos);
	}
}

void PencilTool::released(pair<int, int> pos, bool leftButton, bitset<5> state)
{
	if (leftButton)
	{
		Editor &editor = getEditor();
		SDL_Rect changedArea = largestSDL_Rect(vertices.begin(),
				vertices.end());
		SDL_FillRect(editor.getPreview(), &changedArea, 0x0);
		drawing = false;
		getPicture().addCommand(new DrawLinesCommand(vertices.begin(),
				vertices.end(), editor.getColor(), editor.getCurrentLayer()));
		vertices.clear();
	}
}

void PencilTool::moved(pair<int, int> pos, pair<int, int> offset
		, std::bitset<5> state)
{
	if (drawing && state[BUTTON_LEFT])
	{
		Editor &editor = getEditor();
		pair<int, int> oldPos = vertices.back();

		Graphics g(editor.getPreview());
		g.setColor(editor.getColor());
		g.drawLine(oldPos, pos);
		vertices.push_back(pos);
	}
}

} /* namespace yep */
